﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq.Expressions;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CamlexNET;
using LifeInSharePoint.Common;
using LifeInSharePoint.Common.Base;
using Microsoft.SharePoint;
using System.Web.UI.HtmlControls;

namespace LifeInSharePoint.Blog.Common.WebParts.LISPRecentComments
{
    [ToolboxItemAttribute(false)]
    public class LISPRecentComments : BaseWebPart
    {

        #region Private Properties

        private const string COMMENTSLIST = "Comments";
        private const string CONTENTTYPE = "Life In SharePoint Blog Comment";
        private string transformedXML = null;
        private bool errorFound = false;
        private string errorMessage = null;

        #endregion

        private string _XSLTPath =  "/_layouts/LifeInSharePoint.Blog/xslt/RecentComments.xslt";
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("XSLT Path")]
        [WebDescription("Path the the XSLT")]
        public string XSLTPath
        {
            get { return _XSLTPath; }
            set { _XSLTPath = value; }
        }

        private string _RelSiteUrl = "/blog";
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("Rel Site Url")]
        [WebDescription("Rel Site Url")]
        public string RelSiteUrl
        {
            get { return _RelSiteUrl; }
            set { _RelSiteUrl = value; }
        }

        private int _RowLimit = 4;
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("Row Limit")]
        [WebDescription("Row Limit")]
        public int RowLimit
        {
            get { return _RowLimit; }
            set { _RowLimit = value; }
        }


        protected override void OnInit(EventArgs e)
        {
            this.ChromeType = PartChromeType.None;
            this.ExportMode = WebPartExportMode.All;
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!string.IsNullOrEmpty(XSLTPath))
            {
                processData();
            }
            else
            {
                errorFound = true;
                errorMessage = "XSLT Path is not Defined - Please edit webpart Properties";
            }

        }

        protected override void CreateChildControls()
        {
            if (!errorFound)
            {
                HtmlGenericControl container = new HtmlGenericControl("Div");
                container.InnerHtml = transformedXML;
                this.Controls.Add(container);
            }
            else
            {
                Label errorMsg = new Label();
                errorMsg.Text = errorMessage;
                this.Controls.Add(errorMsg);
            }

        }

        private void processData()
        {
            //Get the SP Web
            SPWeb web = SPContext.Current.Site.RootWeb;

            //Get the List Instance
            SPList newslist = web.Lists[COMMENTSLIST];

            //Get a new SPQuery Instance
            SPQuery workQuery = new SPQuery();
            //Create Expressions for the CAMLEx

            var expressions = new List<Expression<Func<SPListItem, bool>>>();
            expressions.Add(x => ((string)x["ContentType"]) == CONTENTTYPE);
            expressions.Add(x => ((string)x["LISPCommentStatus"]) == "Approved");
            var caml = Camlex.Query().WhereAll(expressions).ToString();

            workQuery.Query = caml + "<OrderBy><FieldRef Name='Modified' Ascending='True'/></OrderBy>";

            SPListItemCollection _workItemCollection = newslist.GetItems(workQuery);

            if (_workItemCollection != null && _workItemCollection.Count > 0)
            {
                DataTable CommentDT = new DataTable("Comment");
                CommentDT.Columns.Add("ID");
                CommentDT.Columns.Add("Name");
                CommentDT.Columns.Add("Date");
                CommentDT.Columns.Add("Website");
                CommentDT.Columns.Add("Comment");
                CommentDT.Columns.Add("Email");
                CommentDT.Columns.Add("PostName");


                foreach (SPListItem _workItem in _workItemCollection)
                {
                    string Name = SPListHelper.GetColumnStringValue(_workItem, "Title");
                    int ID = SPListHelper.GetColumnIntValue(_workItem, "ID");
                    DateTime Date = (DateTime)SPListHelper.GetColumnValue(_workItem, "Modified");
                    string Website = SPListHelper.GetColumnStringValue(_workItem, "LISPCommentWebsite");
                    string Comment = SPListHelper.GetColumnStringValue(_workItem, "LISPCommentMessage");
                    string Email = SPListHelper.GetColumnStringValue(_workItem, "LISPCommentEmail");
                    string PostName = getPostName(Convert.ToInt32(SPListHelper.GetColumnStringValue(_workItem, "LISPCommentPostID")));
                    CommentDT.Rows.Add(ID, Name, Date, Website, Comment, Email, PostName);
                }

                DataSet CommentDS = new DataSet("Comments");
                CommentDS.Tables.Add(CommentDT);
                string resultXML = CommentDS.GetXml();

                transformedXML = SPWebPartHelper.ConvertXML(resultXML, SPContext.Current.Site.Url + XSLTPath);
            }
            else
            {
                DataTable CommentDT = new DataTable("NoComment");
                CommentDT.Columns.Add("Title");
                CommentDT.Rows.Add("No Comments Found");
                DataSet CommentDS = new DataSet("Comments");
                CommentDS.Tables.Add(CommentDT);
                string resultXML = CommentDS.GetXml();
                transformedXML = SPWebPartHelper.ConvertXML(resultXML, SPContext.Current.Site.Url + XSLTPath);
            }
        }

        private string getPostName(int PostID)
        {
            string postName = "";

            //Get the SP Web
            using (SPSite siteCollection = new SPSite(SPContext.Current.Site.RootWeb.Url + RelSiteUrl))
            {
                using (SPWeb web = siteCollection.OpenWeb())
                {

                    //Get the List Instance
                    SPList newslist = web.Lists["Pages"];

                    //Get a new SPQuery Instance
                    SPQuery workQuery = new SPQuery();
                    //Create Expressions for the CAMLEx
                    var expressions = new List<Expression<Func<SPListItem, bool>>>();
                    expressions.Add(x => ((int) x["ID"]) == PostID);
                    var caml = Camlex.Query().WhereAny(expressions).ToString();

                    workQuery.Query = caml;
                    
                    SPListItemCollection _workCollection = newslist.GetItems(workQuery);

                    string Url = SPListHelper.GetColumnStringValue(_workCollection[0], "EncodedAbsUrl");
                    string Title = SPListHelper.GetColumnStringValue(_workCollection[0], "Title");

                    postName = string.Format("<a href='{0}'>{1}</a>",Url, Title);
                }
            }
            return postName;
        }
    }
}